﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：EventConsumer.cs
// 功能描述：TongTongMall
// 
// Create User：jym 2017/02/15
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Configuration;
using TongTongMall.Dependecy;
using TongTongMall.Events;
using TongTongMall.Events.Handlers.Factories;
using TongTongMall.Util.Etc;

namespace TongTongMall.Commanding.Messaging
{
    public class EventConsumer : DisposableObject, IEventConsumer
    {
        private readonly Dictionary<Type, List<IEventHandlerFactory>> eventHandlers;
        private readonly IMessageSubscriber subscriber;

        public ISettingManager SettingManager { get; set; }

        public EventConsumer(IMessageSubscriber subscriber, IEventBus _eventBus)
        {
            this.subscriber = subscriber;
            eventHandlers = _eventBus.GetAllEvents();
            subscriber.MessageReceived += (sender, e) =>
            {
                if (eventHandlers != null)
                {
                    var handleType = eventHandlers.FirstOrDefault(x =>
                    {
                        return x.Key.Name.ToLower() == e.Message.CommandName.ToLower();
                    });
                    if (!handleType.Equals(default(Dictionary<Type, List<IEventHandlerFactory>>)))
                    {
                        _eventBus.Trigger(handleType.Key,
                        (IEventData)e.Message.MessageDataBody.ToObject(handleType.Key));
                    }
                }
            };
        }

        public Dictionary<Type, List<IEventHandlerFactory>> EventHandlers => eventHandlers;

        public IMessageSubscriber Subscriber => subscriber;

    }
}
